import React from 'react';
import {connect} from 'react-redux';
import { Button, Modal, Progress, Icon, message, Select, Input } from 'antd';
import { deepFullCopy, messages } from "share/common";
const InputGroup = Input.Group;
const Option = Select.Option;
import AsyncService from "components/template/async-export/async-service";
import ExportService from 'components/template/export-modal/export-modal.service';

let codeTimer = null;

class AsyncExport extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      progressNum: 0,
      visible: false,
      step: '',
      path: '',
      errorDetail: '',
      timer: '',
      loading: false,
      isSended: false,
      timeNumber: 0,
      codeTemp: [],
      codeCheckConfirming: false,
      token: ''
    };
  }

  handleExport = () => {
    clearInterval(this.state.timer);
    const { codeCheck, company } = this.props;
    if (codeCheck && company.exportSecurity) {
      this.setState({
        codeCheckConfirming: false,
        isSended: false,
        codeTemp: this.encodeEmailOrMobile(),
        visible: true,
        progressNum: 0,
        timeNumber: 0,
        token: '',
        path: "",
        step: 'codeCheck'
      })
    } else {
      this.beginExport();
    }
  };

  beginExport = () => {
    const { params } = this.props;
    let timeStamp = Date.parse(new Date());
    let temp = deepFullCopy(params);
    temp.timeStamp = timeStamp;
    this.setState({ loading: true });
    AsyncService.getExportInfo(temp).then(res => {
      this.setState({ loading: false });
      if(temp.isAsync){
        this.setState({
          visible: true,
          progressNum: 0,
          step: 'pending'
        }, () => {
          this.exportInfoProgress(temp);
        })
      } else {
        window.open(res.data.path);
      }
    }).catch(e => {
      this.setState({ loading: false });
      message.error(e.response.data.message);
    })
  };

  encodeEmailOrMobile = () => {
    const { user } = this.props;
    let result = [];
    if (user.mobile && user.mobile.length > 4) {
      result.push({
        type: 'mobile',
        res: user.mobile.slice(0, 3) + " **** " + user.mobile.slice(user.mobile.length - 4, user.mobile.length),
        login: user.mobile
      });
    }
    if (user.email && user.email.length > 4 && user.email.match(/@/)) {
      result.push({
        type: 'email',
        res: user.email.slice(0, 2) + " **** @" + user.email.split("@")[1],
        login: user.email
      });
    }
    return result;
  };

  exportInfoProgress = temp => {
    const { refresh } = this.props;
    AsyncService.getExportProgress(temp).then(res => {
      this.setState({
        progressNum: res.data && res.data.progress ? parseInt(res.data.progress) : 0,
        path: "",
      },() => {
        if (res.data.status === "SUCCESS") {
          clearInterval(this.state.timer);
          if (refresh) {
            this.setState({ visible: false },() => {
              refresh();
            })
          } else {
            this.setState({
              step: "success",
              path: res.data.path
            })
          }
        } else if (res.data.status === "ERROR") {
          clearInterval(this.state.timer);
          this.setState({
            step: "error",
            path: "",
            errorDetail: res.data.errorDetail
          })
        } else {
          clearInterval(this.state.timer);
          let that = this;
          this.state.timer = setInterval(() => {
            that.exportInfoProgress(temp);
          }, 2000)
        }
      });
    }).catch(() => {
      clearInterval(this.state.timer);
      this.setState({
        step: "error",
        path: ""
      })
    });
  };

  downloadByPath = () => {
    window.open(this.state.path, '_blank');
  };

  getCodeTypeChange = val => {
    let { codeTemp } = this.state;
    codeTemp.map((item, index) => {
      if (item.type === val) {
        let temp = codeTemp[0];
        codeTemp[0] = item;
        codeTemp[index] = temp;
      }
    });
    this.setState({
      codeTemp: codeTemp,
      timeNumber: 0
    })
  };

  codeCheckGetCode = () => {
    const { codeTemp } = this.state;
    let params = {
      type: codeTemp[0].type,
      login: codeTemp[0].login
    };
    this.setState({
      isSended: true,
      timeNumber: 60
    });
    ExportService.getCode(params)
      .then(res => {
        clearInterval(codeTimer);
        codeTimer = setInterval(() => {
          let timeNumber = this.state.timeNumber;
          timeNumber--;
          if (timeNumber === 0) {
            clearInterval(codeTimer);
          }
          this.setState({
            timeNumber
          })
        }, 1000);
        message.success(messages('components.key447'/*发送成功*/))
      })
  };

  tokenChange = (e) => {
    this.setState({
      token: e.target.value
    })
  };

  codeCheckConfirm = () => {
    const { codeTemp, token } = this.state;
    this.setState({
      codeCheckConfirming: true
    });
    let params = {
      login: codeTemp[0].login,
      type: codeTemp[0].type,
      token
    };
    ExportService.checkCode(params)
      .then(res => {
        this.setState({
          codeCheckConfirming: false,
          step: 'pending',
          visible: true,
          progressNum: 0,
          path:  "",
          token: ""
        }, () => {
          this.beginExport();
        });
      })
      .catch(()=>{
        this.setState({
          codeCheckConfirming: false
        })
      })
  };

  renderContentByStep = () => {
    const { step, progressNum, errorDetail, codeTemp, isSended, timeNumber, codeCheckConfirming, token } = this.state;
    switch (step) {
      case "codeCheck": {
        return (
          <div className="step-code-check">
            <div className="title-wrap"> {messages('components.key448'/*安全验证*/)}
              <div className="title-desc-wrap">{messages('components.key449'/*为确保数据安全，请进行安全验证*/)}</div>
            </div>
            <div className="row">
              <div className="row-int-wrap">
                <InputGroup compact>
                  <Select key={codeTemp[0].type} style={{width: '30%'}} defaultValue={codeTemp[0].type}
                          onChange={this.getCodeTypeChange}>
                    {
                      codeTemp.filter(item => item.type === 'mobile').length > 0 &&
                      <Option value="mobile">{messages('components.key450'/*手机*/)}</Option>
                    }
                    {
                      codeTemp.filter(item => item.type === 'email').length > 0 &&
                      <Option value="email">{messages('components.key451'/*邮箱*/)}</Option>
                    }
                  </Select>
                  <Input style={{width: '70%'}}
                         disabled={true}
                         value={codeTemp[0].res}/>
                </InputGroup>
              </div>
              <div className="row-btn-wrap">
                {!isSended && <Button
                  onClick={this.codeCheckGetCode}
                  type="primary"
                  disabled={timeNumber > 0}>
                  {messages('components.key452'/*验证码*/)} {timeNumber > 0 ? timeNumber : ""}
                </Button>}
                {isSended && <Button
                  onClick={this.codeCheckGetCode}
                  type="primary"
                  disabled={timeNumber > 0}>
                  {messages('components.key453'/*重新获取*/)} {timeNumber > 0 ? timeNumber : ""}
                </Button>}
              </div>
              <div className="clear"></div>
            </div>
            <div className="row">
              <Input placeholder={messages('components.key454'/*请输入验证码*/)}
                     value={token}
                     onChange={this.tokenChange}/>
            </div>

            <div className="btn-wrap">
              <Button type="primary"
                      disabled={!(token && token.length > 0) || codeCheckConfirming}
                      onClick={this.codeCheckConfirm}> {messages('components.key455'/*确认*/)}
              </Button>
              &nbsp;&nbsp;&nbsp;
              <Button onClick={this.handleCancel}> {messages('common.cancel')/*取消*/}
              </Button>
            </div>
          </div>
        );
        break
      }
      case "pending": {
        return (
          <div className="step-pending">
            <div className="title-wrap">
              <div>
                {messages('components.key456'/*数据加载中...*/)}
              </div>
            </div>
            <div className="progress-wrap">
              <Progress percent={progressNum} status="active"/>
            </div>
            <div className="loading-tip">
              <div>
                {messages('components.key1046')/*文件生成中，请勿关闭或者离开当前页面*/}
              </div>
            </div>
            <div className="btn-wrap">
              <Button type="primary"
                      onClick={this.handleCancel}>
                {messages('common.cancel')/*取消*/}
              </Button>
            </div>
          </div>
        );
        break
      }
      case "success": {
        return (
          <div className="step-success">
            <div className="title-wrap">
              <div>
                <Icon className="icon-success" type="check-circle"/>
                {messages('components.key459'/*加载成功，请点击下载*/)}
              </div>
            </div>
            <div className="progress-wrap">
              <Progress percent={progressNum} status="active"/>
            </div>
            <div className="btn-wrap">
              <Button type="primary" onClick={this.downloadByPath}>
                {messages('components.key460'/*下载*/)}
              </Button>
              <Button onClick={this.handleCancel} style={{ marginLeft: '5px' }}>
                {messages('components.key461'/*关闭*/)}
              </Button>
            </div>
          </div>
        );
        break
      }
      case "error": {
        return (
          <div className="step-error">
            <div className="title-wrap">
              <div>
                <Icon className="icon-error" type="close-circle"/>
                {messages('components.key462'/*加载失败，请重试*/)}
              </div>
            </div>
            <div className="progress-wrap">
              <Progress percent={50} status="active"/>
            </div>
            <div className="loading-tip">
              <div>
                {errorDetail}
              </div>
            </div>
            <div className="btn-wrap">
              <Button type="primary" onClick={this.handleCancel} style={{ marginLeft: '5px' }}>
                {messages('components.key461'/*关闭*/)}
              </Button>
            </div>
          </div>
        );
        break
      }
    }
  };

  handleCancel = () => {
    clearInterval(this.state.timer);
    this.setState({ visible: false, token: "", isSended: false });
  };

  render() {
    const { visible, loading } = this.state;
    const { disabled, title, style } = this.props;
    return (
      <div style={style}>
        <Button type={'primary'} disabled={disabled} onClick={this.handleExport} loading={loading}>{title}</Button>
        <Modal
          width={500}
          maskClosable={false}
          closable={false}
          keyboard={false}
          className="export-modal-wrap-modal"
          title={null}
          destroyOnClose
          visible={visible}
          footer={null}
        >
          <div className="export-modal">
            {this.renderContentByStep()}
          </div>
        </Modal>
      </div>
    );
  }
}

AsyncExport.propTypes = {
  disabled: React.PropTypes.bool,
  title: React.PropTypes.string,
  params: React.PropTypes.object.isRequired,
  refresh: React.PropTypes.func,
  style: React.PropTypes.object,
  codeCheck: React.PropTypes.bool
};

AsyncExport.defaultProps = {
  disabled: false,
  title: messages('components.key1004')/*生成PDF*/,
  codeCheck: false
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    company: state.login.company
  }
}

export default connect(mapStateToProps)(AsyncExport);



